import { NUpload } from "naive-ui";
import type { UploadProps, UploadInst } from "naive-ui";
import type { BaseComponentType, OmitHTMLAttributes } from "../types";
import { getSlotsDom } from "../utils";
export type UploadFactoryConstructorType = {
  props?: UploadProps;
  attrs?: OmitHTMLAttributes<"onChange" | "onError">;
  defaultSlot?: BaseComponentType;
};
export class UploadFactory {
  private props: UploadProps = {};
  private attrs: OmitHTMLAttributes<"onChange" | "onError"> = {};
  private defaultSlot: BaseComponentType = null;
  protected domRef: UploadInst | null = null;

  constructor(data?: UploadFactoryConstructorType) {
    if (data?.props) this.setProps(data.props);
    if (data?.attrs) this.setAttrs(data.attrs);
    if (data?.defaultSlot) this.setDefault(data.defaultSlot);
  }

  setAttrs(attrs: OmitHTMLAttributes<"onChange" | "onError">) {
    this.attrs = attrs;
    return this;
  }
  setProps(props: UploadProps) {
    this.props = props;
    return this;
  }
  setDefault(component: BaseComponentType) {
    this.defaultSlot = component;
    return this;
  }
  clear() {
    this.domRef?.clear();
  }

  openOpenFileDialog() {
    this.domRef?.openOpenFileDialog();
  }
  submit(fileId?: string) {
    this.domRef?.submit(fileId);
  }
  create() {
    return (
      <NUpload
        ref={(el: HTMLElement) => {
          this.domRef = el as unknown as UploadInst;
        }}
        {...this.attrs}
        {...this.props}
      >
        {{
          default: () => getSlotsDom(this.defaultSlot),
        }}
      </NUpload>
    );
  }
}
